<template>
  <view class="container">
    <!-- 聊天内容区域 -->
    <scroll-view 
      scroll-y 
      class="chat-content" 
      :scroll-into-view="scrollToBottomId"
      :scroll-top="scrollTop"
    >
      <view 
        v-for="(msg, index) in messages"
        :key="index"
        :id="'msg-' + index"
        class="message-item"
        :class="msg.isSelf ? 'right' : 'left'"
      >
        <view class="bubble">{{ msg.content }}</view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <input v-model="newMsg" @confirm="sendMsg" placeholder="输入消息" />
      <button @tap="sendMsg">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { useMainStore } from '@/store'
const store = useMainStore()

// 测试数据
const messages = ref([
  { isSelf: false, content: '您好，有什么可以帮您？' },
  { isSelf: true, content: '我想咨询产品信息' },
  { isSelf: false, content: '请说具体需求' },
  { isSelf: true, content: '需要技术参数文档' }
])
messages.value = store.messages
const newMsg = ref('')
const scrollToBottomId = ref('')
const scrollTop = ref(0)

function sendMsg() {
  if (!newMsg.value) return
  
  // 添加新消息
  messages.value.push({
    isSelf: true,
    content: newMsg.value
  })
  
  newMsg.value = ''
  
  // 滚动到底部
  scrollToBottom()
}

function scrollToBottom() {
  nextTick(() => {
    scrollToBottomId.value = 'msg-' + (messages.value.length - 1)
    // 通过改变 scrollTop 确保滚动生效
    scrollTop.value += 1
  })
}

// 初始化时滚动到底部
setTimeout(scrollToBottom, 100)
</script>

<style scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.chat-content {
  flex: 1;
  padding: 20rpx;
  background-color: #f0f0f0;
}

.message-item {
  margin: 20rpx 0;
  display: flex;
}

/* 左侧消息样式 */
.message-item.left {
  justify-content: flex-start;
}

/* 右侧消息样式 */
.message-item.right {
  justify-content: flex-end;
}

.bubble {
  max-width: 70%;
  padding: 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
  position: relative;
}

.message-item.right .bubble {
  background-color: #1d4ed8;
  color: white;
}

.input-area {
  height: 100rpx;
  padding: 20rpx;
  background: white;
  display: flex;
  gap: 20rpx;
  border-top: 1px solid #ddd;
}

.input-area input {
  flex: 1;
  border: 1px solid #ddd;
  padding: 10rpx;
  border-radius: 8rpx;
}
</style>